package com.cl.util;

import com.cl.auth.stateless.StatelessUser;
import com.cl.entity.UOrg;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.cl.dao.SearchDao;
import com.cl.entity.AccessToken;
import com.cl.entity.UUser;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Service
public class CommonUtil {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SearchDao<?> searchDao;

    @Value("#{applicationProperties['cas.baseDn']}")
    protected String baseDn;

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public UUser getUser() {
        Subject subject = SecurityUtils.getSubject();
        UUser user = (UUser) subject.getPrincipal();
        if (user == null) {
            user = new UUser();
            try {
                SecurityUtils.getSubject().logout();
            } catch (UnavailableSecurityManagerException e) {

            } catch (InvalidSessionException e) {

            }
        }
        return user;
    }

    /**
     * 获取当前登录用户
     * @return　用户
     */
    public UUser getCurrentUser() {
    	return getUser();
//        // 直接使用在内在中存放的用户信息
//        StatelessUser user = (StatelessUser) RequestContextHolder.currentRequestAttributes().getAttribute(Constants.USER_KEY, RequestAttributes.SCOPE_SESSION);
//        return (UUser)user;
    }

    /**
     * 获取当前登录用户的固定格式ID，格式如：许冰彬[cn=420683198011215815,org=资料信息中心]
     * @return　返回ID
     */
    public String getCurrentUserID(){
        String userId = "";
        UUser user = getCurrentUser();
        if (user != null) {
            userId += user.getName()
                    + "["
                    + user.getUserId()
                    + ",org="
                    + user.getOrgName()
                    + "]";
        }
        return userId;
    }

    public String getCurrentSimpleUserID(){
        String userId = "";
        UUser user = getCurrentUser();
        if (user != null) {
            userId += user.getName()
                    + "["
                    + user.getUserId()
                    + "]";
        }
        return userId;
    }


    /**
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
     *
     * @param request
     * @return
     */
    public final String getIpAddress(HttpServletRequest request) {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址

        String ip = request.getHeader("X-Forwarded-For");
        if (logger.isInfoEnabled()) {
            logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
                if (logger.isInfoEnabled()) {
                    logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);
                }
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
                if (logger.isInfoEnabled()) {
                    logger.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);
                }
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
                if (logger.isInfoEnabled()) {
                    logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);
                }
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                if (logger.isInfoEnabled()) {
                    logger.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);
                }
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();

                if (logger.isInfoEnabled()) {
                    logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);
                }
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return "0:0:0:0:0:0:0:1".equals(ip)?"127.0.0.1":ip;
    }

    /**
     * 通过orgId获取用户所处部门信息（用户所在部门+所在科室：如何存在科室的话）
     * @param orgId　部门ID
     * @return 部门信息
     */
    public String getUserAllOrgNameByID(String orgId){
        String orgName = "";
        UOrg org = searchDao.getOrgById(orgId);
        String parentOrg = baseDn.replaceAll("%3D", "=");
        if (org != null) {
            if (parentOrg.equals(org.getParentorgid())) {
                orgName = org.getOrgname();
            } else {
                orgName += org.getOrgname();
                UOrg childOrg = searchDao.getOrgById(org.getParentorgid());
                if (childOrg != null && childOrg.getOrgname() != null) {
                    orgName += ",";
                    orgName += childOrg.getOrgname();
                }
            }
        }
        return orgName;
    }

    /**
     * 通过orgId获取用户所处部门信息 (仅包括部门信息)
     * @param orgId　部门ID
     * @return　部门信息 (仅包括部门信息)　
     */
    public String getUserOrgNameByID(String orgId){
        String orgName = "";
        UOrg org = searchDao.getOrgById(orgId);
        String parentOrg = baseDn.replaceAll("%3D", "=");
        if (org != null) {
            if (parentOrg.equals(org.getParentorgid())) {
                orgName = org.getOrgname();
            } else {
                orgName = getUserOrgNameByID(org.getParentorgid());
            }
        }
        return orgName;
    }

    /**
     *　通过orgId获取用户所处科室信息 (仅包括科室信息，可能为空，部门人员仅在部门不在科室)
     * @param officeId
     * @return
     */
    public String getUserOfficeNameByID(String officeId){
        String officeName = "";
        UOrg org = searchDao.getOrgById(officeId);
        String parentOrg = baseDn.replaceAll("%3D", "=");
        if (org != null) {
            if (!parentOrg.equals(org.getParentorgid())) {
                officeName = org.getOrgname();
            }
        }
        return officeName;
    }

}
